const moment = require('moment')
const md5 = require('md5')
const { mysqlApi } = require('../model/db')
const messageInfo = require('../utils/messageInfo')

// 查询用户列表（权限查询）
exports.UserList = async (req, res) => {
    const page = Number(req.query.page) || 1
    const size = Number(req.query.size) || 5
    let dataSql = ''
    let totalSizeSql = ''
    if (req.params.level) {
        dataSql = `SELECT * FROM users WHERE level = '${req.params.level}' LIMIT ${(page - 1) * size}, ${size};`
        totalSizeSql = `SELECT COUNT(*) from users WHERE level = '${req.params.level}';`
    } else {
        dataSql = `SELECT * FROM users LIMIT ${(page - 1) * size}, ${size};`
        totalSizeSql = `SELECT COUNT(*) from users;`
    }
    try {
        const data = await mysqlApi(dataSql)
        const totalSize = (await mysqlApi(totalSizeSql))[0]["COUNT(*)"]
        const totalPages = Math.ceil(totalSize / size)
        res.status(200).json(messageInfo({ page, size, totalPages, data, totalSize }, '200', '查询成功'))
    } catch (error) {
        res.status(400).json(messageInfo(error, '400', '查询失败'))
    }
}


// 根据id查询用户
exports.UserById = async (req, res) => {
    const sqlStr = `SELECT * FROM users WHERE is_show = 1 and user_id = '${req.params.id}';`
    try {
        const data = await mysqlApi(sqlStr)
        if (data.length == 0) {
            res.status(200).json(messageInfo(null, '204', '查询成功'))
        } else {
            res.status(200).json(messageInfo(data, '200', '查询成功'))
        }
    } catch (error) {
        res.status(400).json(messageInfo(error, '400', '查询失败'))
    }
}

// 添加用户
exports.UserAdd = async (req, res) => {
    const body = req.body
    const searchSql = `SELECT * FROM users WHERE username = '${body.username}';`
    const searchData = await mysqlApi(searchSql)
    if (searchData.length == 0) {
        body.password = md5(body.password)
        const sqlStr = `
            INSERT INTO users (
                user_id,
                username,
                password,
                level,
                phone,
                age,
                address,
                avatar,
                is_show,
                is_delete,
                create_time
            )
            VALUES(    
                REPLACE(MD5(UUID()), '-', ''),
                "${body.username}",
                "${body.password}",
                "${body.level}",
                "${body.phone}",
                "${body.age ? body.age : ''}",
                "${body.address ? body.address : ''}",
                "${body.avatar ? body.avatar : ''}",
                "${body.is_show ? body.is_show : 1}",
                "${body.is_delete ? body.is_delete : 1}",
                "${moment().format('YYYY-MM-DD HH:mm:ss')}"
                );
            `
        try {
            const data = await mysqlApi(sqlStr)
            res.status(200).json(messageInfo(data, '201', '添加成功'))
        } catch (error) {
            res.status(400).json(messageInfo(error, '400', '添加失败'))
        }
    } else {
        res.status(400).json(messageInfo(null, '422', '用户已经存在'))
    }

}

// 模糊查询
exports.UserLike = async (req, res) => {
    const page = Number(req.query.page) || 1
    const size = Number(req.query.size) || 5
    const sqlStr1 = `SELECT * from users WHERE ${req.params.class} LIKE "%${req.params.keyword}%" LIMIT ${(page - 1) * size}, ${size};`
    const sqlStr2 = `SELECT COUNT(*) from users WHERE ${req.params.class} LIKE "%${req.params.keyword}%";`
    try {
        const data = await mysqlApi(sqlStr1)
        if (data.length == 0) {
            return res.status(200).json(messageInfo({ data: [] }, '204', '没有数据'))
        } else {
            const totalSize = (await mysqlApi(sqlStr2))[0]["COUNT(*)"]
            const totalPages = Math.ceil(totalSize / size)
            return res.status(200).json(messageInfo({ page, size, totalPages, data, totalSize }, '200', '成功获取数据'))
        }
    } catch (error) {
        console.log(error);
        res.status(400).json(messageInfo(error, '400', '查找失败'))
    }
}


// 删除用户
exports.UserDelete = async (req, res) => {
    const sqlStr1 = `SELECT * FROM users WHERE is_delete = 1 and user_id = '${req.params.id}';`
    const sqlStr2 = `DELETE from users WHERE is_delete=1 and user_id='${req.params.id}'`
    try {
        const data1 = await mysqlApi(sqlStr1)
        if (data1.length == 0) {
            return res.status(400).json(messageInfo(data1, '400', '用户不存在,或无法删除'))
        }
        const data2 = await mysqlApi(sqlStr2)
        return res.status(200).json(messageInfo(data2, '204', '删除成功'))
    } catch (error) {
        res.status(400).json(messageInfo(error, '400', '用户不存在，或无法删除'))
    }
}

//  编辑用户
exports.UserEdit = async (req, res) => {
    try {
        const sqlStr1 = `SELECT * FROM users WHERE user_id = '${req.params.id}';`
        const data1 = await mysqlApi(sqlStr1)
        // 根据id判断用户是否存在
        if (data1.length == 0) {
            return res.status(400).json(messageInfo(data1, '404', '用户不存在'))
        }
        // 判断用户权限
        if (data1.level == '0' || data1.level == '1') {
            return res.status(400).json(messageInfo(null, '405', '用户权限不足'))
        }
        // 判断密码是否正确 
        if (data1[0].password != md5(req.body.old_password)) {
            return res.status(400).json(messageInfo(null, '403', '原始密码不正确'))
        }
        data1.avatar = data1.avatar != 'undefined' ? data1.avatar : ''
        // 修改账户
        const sqlStr3 = `
        UPDATE users
        SET 
            username = '${req.body.username}',
            password = '${md5(req.body.new_password)}',
            phone = '${req.body.phone}',
            age = '${req.body.age ? req.body.age : data1.age}',
            address = '${req.body.address ? req.body.address : data1.address}',
            avatar = '${req.body.avatar ? req.body.avatar : data1.avatar}'
        WHERE
            user_id = '${req.params.id}';
        `
        const data3 = await mysqlApi(sqlStr3)
        return res.status(200).json(messageInfo(data3, '202', '修改成功'))
    } catch (error) {
        res.status(400).json(messageInfo(error, '400', '修改失败'))
    }
}

// 修改用户状态
exports.UserStatus = async (req, res) => {
    try {
        const sqlStr1 = `SELECT * FROM users WHERE user_id = '${req.params.id}';`
        const data1 = await mysqlApi(sqlStr1)
        // 判断用户是否存在
        if (data1.length == 0) {
            return res.status(400).json(messageInfo(data1, '404', '用户不存在'))
        }
        // 判断状态是否发生改变
        if (data1[0][req.params.class] == req.params.value) {
            return res.status(200).json(messageInfo(data1, '200', '无状态改变'))
        }
        const sqlStr3 = `
        UPDATE users
        SET 
            ${req.params.class} = '${req.params.value}'
        WHERE
            user_id = '${req.params.id}';
        `
        const data3 = await mysqlApi(sqlStr3)
        return res.status(200).json(messageInfo(data3, '202', '修改成功'))
    } catch (error) {
        res.status(400).json(messageInfo(error, '400', '修改失败'))
    }
}
